<template>
  <a-config-provider :locale="locale">
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <!-- 搜索区域 -->
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="24">
              <a-form-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入单据编号" v-model="queryParam.billNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="往来单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select placeholder="请选择往来单位" showSearch allow-clear optionFilterProp="children" v-model="queryParam.organId">
                  <a-select-option v-for="(item,index) in organList" :key="index" :value="item.id">
                    {{ item.supplier }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-range-picker
                  style="width:100%"
                  v-model="queryParam.createTimeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onDateChange"
                  @ok="onDateOk"
                />
              </a-form-item>
            </a-col>
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="searchQuery">查询</a-button>
                <a-button style="margin-left: 8px" v-print="'#reportPrint'" icon="printer">打印</a-button>
                <a-button style="margin-left: 8px" @click="exportExcel" icon="download">导出</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </a-col>
              </span>
            <template v-if="toggleSearchStatus">
              <a-col :md="6" :sm="24">
                <a-form-item label="财务人员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择财务人员" showSearch allow-clear optionFilterProp="children" v-model="queryParam.handsPersonId">
                    <a-select-option v-for="(item,index) in personList" :key="index" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="操作员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择操作员" showSearch allow-clear optionFilterProp="children" v-model="queryParam.creator">
                    <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                      {{ item.userName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="账户信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择账户信息" showSearch allow-clear :dropdownMatchSelectWidth="false"
                            optionFilterProp="children" v-model="queryParam.accountId">
                    <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="单据类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.type" allow-clear placeholder="请选择单据类别">
                    <a-select-option value="收款">收款</a-select-option>
                    <a-select-option value="付款">付款</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="orgaTree.length">
                <a-form-item label="机构" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select style="width:100%" allow-clear :treeData="orgaTree"
                                 v-model="queryParam.organizationId" placeholder="请选择机构">
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="明细单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入采购或销售单号" v-model="queryParam.billNumber"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入备注" v-model="queryParam.remark"></a-input>
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
      </div>
      <!-- table区域-begin -->
      <div style="width:100%; min-width:1550px">
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :components="handleDrag(columns)"
            :pagination="false"
            :loading="loading"
            @change="handleTableChange">
            <span slot="customTitle">
              <a-popover trigger="click" placement="right">
                <template slot="content">
                  <a-checkbox-group @change="onColChange" v-model="settingDataIndex" :defaultValue="settingDataIndex">
                    <a-row style="width: 600px">
                      <template v-for="(item,index) in defColumns">
                        <template>
                          <a-col :span="6">
                            <a-checkbox :value="item.dataIndex" v-if="item.dataIndex==='rowIndex'" disabled></a-checkbox>
                            <a-checkbox :value="item.dataIndex" v-if="item.dataIndex!=='rowIndex'">
                              <j-ellipsis :value="item.title" :length="10"></j-ellipsis>
                            </a-checkbox>
                          </a-col>
                        </template>
                      </template>
                    </a-row>
                    <a-row style="padding-top: 10px;">
                      <a-col>
                        恢复默认列配置：<a-button @click="handleRestDefault" type="link" size="small">恢复默认</a-button>
                      </a-col>
                    </a-row>
                  </a-checkbox-group>
                </template>
                <a-icon type="setting" />
              </a-popover>
            </span>
            <span slot="billNoCustomRender" slot-scope="text, record">
              <a @click="myHandleFinancialDetail(record)">{{record.billNo}}</a>
            </span>
            <span slot="billNumberCustomRender" slot-scope="text, record">
              <a @click="myHandleBillDetail(record)">{{record.billNumber}}</a>
            </span>
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
            <a-col :md="24" :sm="24">
              <a-pagination @change="paginationChange" @showSizeChange="paginationShowSizeChange"
                size="small"
                show-size-changer
                :showQuickJumper="true"
                :page-size="ipagination.pageSize"
                :page-size-options="ipagination.pageSizeOptions"
                :total="ipagination.total"
                :show-total="(total, range) => `共 ${total-parseInt(total/ipagination.pageSize)} 条`">
                <template slot="buildOptionText" slot-scope="props">
                  <span>{{ props.value-1 }}条/页</span>
                </template>
              </a-pagination>
            </a-col>
          </a-row>
        </section>
      </div>
      <!-- table区域-end -->
      <financial-detail ref="modalFinancialDetail"></financial-detail>
      <bill-detail ref="modalBillDetail"></bill-detail>
    </a-card>
  </a-config-provider>
</template>

<script>
  import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
  import FinancialDetail from '@/components/tools/FinancialDetail'
  import BillDetail from '@/components/tools/BillDetail'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { updateTheme } from '@/components/tools/setting'
  import { DEFAULT_COLOR } from "@/store/mutation-types"
  import {findBySelectOrgan, getPersonByType, getUserList, findBillDetailByNumber, getAccount, getAllOrganizationTreeByUser} from '@/api/api'
  import { getFormatDate, getPrevMonthFormatDate } from '@/utils/util'
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import moment from 'moment'
  import Vue from 'vue'
  export default {
    name: 'MoneyDetail',
    mixins:[JeecgListMixin],
    components: {
      FinancialDetail,
      BillDetail,
      JEllipsis
    },
    data () {
      return {
        locale: zhCN,
        // 查询条件
        queryParam: {
          billNo: "",
          organId: undefined,
          beginTime: getPrevMonthFormatDate(3),
          endTime: getFormatDate(),
          createTimeRange: [moment(getPrevMonthFormatDate(3)), moment(getFormatDate())],
          creator: undefined,
          handsPersonId: undefined,
          accountId: undefined,
          type: undefined,
          organizationId: undefined,
          billNumber: "",
          remark: ""
        },
        ipagination:{
          pageSize: 11,
          pageSizeOptions: ['11', '21', '31', '101', '201']
        },
        supList: [],
        orgaTree: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 10 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14 },
        },
        pageName: 'moneyDetail',
        // 默认索引
        defDataIndex:['rowIndex','billNo','organName','handsPersonName','userName','accountName','type','billNumber','needDebt',
          'moneyInAmount','moneyOutAmount','billTimeStr','remark'],
        // 默认列
        defColumns: [
          {
            dataIndex: 'rowIndex', width:40, align:"center", slots: { title: 'customTitle' },
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {
            title: '单据编号', dataIndex: 'billNo', width: 100,
            scopedSlots: { customRender: 'billNoCustomRender' },
          },
          { title: '往来单位', dataIndex: 'organName',width:140, ellipsis:true},
          { title: '财务人员', dataIndex: 'handsPersonName',width:80, ellipsis:true},
          { title: '操作员', dataIndex: 'userName',width:60, ellipsis:true},
          { title: '账户信息', dataIndex: 'accountName',width:80, ellipsis:true},
          { title: '单据类别', dataIndex: 'type',width:60},
          {
            title: '采购或销售单号', dataIndex: 'billNumber', width: 110,
            scopedSlots: { customRender: 'billNumberCustomRender' },
          },
          { title: '原欠款', dataIndex: 'needDebt',width:80},
          { title: '收款', dataIndex: 'moneyInAmount',width:80},
          { title: '付款', dataIndex: 'moneyOutAmount',width:80},
          { title: '单据日期 ', dataIndex: 'billTimeStr',width:80},
          { title: '备注', dataIndex: 'remark',width:160, ellipsis:true}
        ],
        url: {
          list: "/api/plugin/money-detail/moneyDetail/getList"
        }
      }
    },
    created() {
      this.initOrgan()
      this.initPerson()
      this.initUser()
      this.initAccount()
      this.loadAllOrgaData()
      this.initColumnsSetting()
    },
    mounted () {
      this.primaryColor = Vue.ls.get(DEFAULT_COLOR)
      updateTheme(this.primaryColor)
    },
    methods: {
      moment,
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize%10===1 ? this.ipagination.pageSize-1 : this.ipagination.pageSize;
        return param;
      },
      myHandleFinancialDetail(record) {
        record.id = record.billId
        this.$refs.modalFinancialDetail.show(record, record.type);
        this.$refs.modalFinancialDetail.title="详情";
      },
      myHandleBillDetail(record) {
        findBillDetailByNumber({ number: record.billNumber }).then((res) => {
          if (res && res.code === 200) {
            this.$refs.modalBillDetail.show(res.data, res.data.subType + res.data.type);
            this.$refs.modalBillDetail.title="详情";
          }
        })
      },
      initOrgan() {
        findBySelectOrgan({}).then((res)=>{
          if(res) {
            this.organList = res;
          }
        });
      },
      initPerson() {
        getPersonByType({type:'财务员'}).then((res)=>{
          if(res && res.code === 200) {
            this.personList = res.data.personList;
          }
        })
      },
      initUser() {
        getUserList({}).then((res)=>{
          if(res) {
            this.userList = res;
          }
        });
      },
      initAccount() {
        getAccount().then((res)=>{
          if(res && res.code === 200) {
            this.accountList = res.data.accountList
          }
        })
      },
      loadAllOrgaData(){
        let that = this
        let params = {}
        getAllOrganizationTreeByUser(params).then((res)=>{
          if(res){
            that.orgaTree = res
          }
        })
      },
      onDateChange: function (value, dateString) {
        this.queryParam.beginTime=dateString[0]
        this.queryParam.endTime=dateString[1]
        if(dateString[0] && dateString[1]) {
          this.queryParam.createTimeRange = [moment(dateString[0]), moment(dateString[1])]
        }
      },
      onDateOk(value) {
        console.log(value);
      },
      exportExcel() {
        let list = []
        let head = '单据编号,往来单位,财务人员,操作员,账户信息,单据类别,采购或销售单号,原欠款,收款,付款,单据日期,备注'
        for (let i = 0; i < this.dataSource.length; i++) {
          let item = []
          let a = this.dataSource[i]
          item.push(a.billNo, a.organName, a.handsPersonName, a.userName, a.accountName, a.type, a.billNumber,
            a.needDebt, a.moneyInAmount, a.moneyOutAmount, a.billTimeStr, a.remark)
          list.push(item)
        }
        let tip = '单据日期：' + this.queryParam.beginTime + '~' + this.queryParam.endTime
        this.handleExportXlsPost('收付款明细', '收付款明细', head, tip, list)
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less'
</style>